//
//  UIStandardEditTableView.m
//  vhStressECG
//
//  Created by jia yu on 2021/11/7.
//

#import "UIStandardEditTableView.h"
#import "UIStandardEditTableViewCell.h"
#import <vhECGTools/vhECGTools.h>
@interface UIStandardEditTableView()<UITableViewDelegate,UITableViewDataSource>{
    
}
@end

@implementation UIStandardEditTableView
@synthesize itemsArray;
@synthesize scale;

-(id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    self = [super initWithFrame:frame style:style];
    if (self){
        scale = 1.f;
        self.delegate = self;
        self.dataSource = self;
    }
    return self;
}

-(void)addItem:(NSString *)item{
    [itemsArray insertObject:item atIndex:self.indexPathForSelectedRow.row];
    [self reloadData];
    return;
}

-(void)removeItem{
    if (nil == self.indexPathForSelectedRow){
        return;
    }
    [self beginUpdates];
    [itemsArray removeObjectAtIndex:self.indexPathForSelectedRow.row];
    [self deleteRowsAtIndexPaths:@[self.indexPathForSelectedRow] withRowAnimation:UITableViewRowAnimationFade];
    [self endUpdates];
    return;
}

-(void)moveUp{
    NSInteger from = self.indexPathForSelectedRow.row;
    NSInteger to = from - 1;
    if (to < 0){
        return;
    }
    [itemsArray exchangeObjectAtIndex:from withObjectAtIndex:to];
    [self reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:to inSection:0];
    [self selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}

-(void)moveDown{
    NSInteger from = self.indexPathForSelectedRow.row;
    NSInteger to = from + 1;
    if (to >= itemsArray.count){
        return;
    }
    [itemsArray exchangeObjectAtIndex:from withObjectAtIndex:to];
    [self reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:to inSection:0];
    [self selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSections{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return itemsArray.count;
}

-(UIStandardEditTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"EditTableViewCell";
    UIStandardEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (nil == cell){
        cell = [[UIStandardEditTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier withScale:scale];
    }
    cell.text =[itemsArray objectAtIndex:indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.f * scale;
}
@end
